﻿using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Zhao.Common.Helper;
using Zhao.IServer;
using Zhao.IServer.Events;
using Zhao.IServer.Log;
using Zhao.Models.AppletDto;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Repository.Base;
using Zhao.Repository.UnitOfWork;

namespace Zhao.Service.Events
{
    /// <summary>
    /// 活动主表
    ///</summary>
    public class ActivitiesServer : BaseService<Activities>, IActivitiesServer
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogsServer _logs;
        public ActivitiesServer(IBaseRepository<Activities> baseDal, IUnitOfWork unitOfWork, ILogsServer logs) : base(baseDal, unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _logs = logs;
        }


        public async Task<PageModel<ActivitiesDTO>> ActivitiQueryPageModel(Expression<Func<Activities, Venues, FieldTypes, bool>> expressionable, int pageIndex, int pageSize)
        {
            //获取总条数
            RefAsync<int> totalCount = 0;

            var list = await _Client.Queryable<Activities>()
                .LeftJoin<Venues>((a, b) => a.VenueID == b.VenueID)
                .LeftJoin<FieldTypes>((a, b, c) => a.TypeId == c.FieldTypeID)
                .WhereIF(expressionable != null, expressionable)
                .Select((a, b, c) => new ActivitiesDTO
                {
                    aId = a.ActivityID,
                    vName = b.VenueName,
                    tName = c.FieldTypeName,
                    Title = a.Title,
                    CreatedAt = a.CreatedAt,
                    Description = a.Description,
                    MaxNumber = a.MaxNumber,
                    StartTime = a.StartTime,
                    EndTime = a.EndTime,
                    DisplayDate = a.DisplayDate,
                    Image = a.Image,
                    Price = a.Price,
                    DepositAmount = a.DepositAmount,
                    IsSettled = a.IsSettled,
                    SettlementTime = a.SettlementTime,
                    tId = a.TypeId,
                    vId = a.VenueID,
                    Status = a.Status,
                    Deadline = a.Deadline,
                    IsLadyDiscountEnabled = a.IsLadyDiscountEnabled,
                    LadyDiscountType = a.LadyDiscountType,
                    LadyDiscountValue = a.LadyDiscountValue,
                    PriceType = a.PriceType,
                    CancelReason = a.CancelReason
                }).ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);

            int totalPage = Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal()).ObjToInt();

            return new PageModel<ActivitiesDTO>() { count = totalCount, PageCount = totalPage, PageIndex = pageIndex, PageSize = pageSize, data = list, code = totalCount == 0 ? -1 : 0, msg = totalCount == 0 ? "未查询到任何数据" : "" };
        }


        /// <summary>
        /// 取消活动并退款给所有报名用户
        /// </summary>
        /// <param name="activityId">活动ID</param>
        /// <param name="operatorId">操作人ID</param>
        /// <param name="cancelReason">取消原因</param>
        /// <returns>取消结果</returns>
        public async Task<ApiResult> CancelActivityAsync(int activityId, int operatorId, string cancelReason)
        {
            var result = new ApiResult { Success = false };

            try
            {
                // 查询活动信息
                var activity = await _Client.Queryable<Activities>()
                    .Where(a => a.ActivityID == activityId)
                    .FirstAsync();

                if (activity == null)
                {
                    result.Message = "活动不存在";
                    return result;
                }

                // 检查活动状态，只有待发布(0)和已上线(1)的活动可以取消
                if (activity.Status != 0 && activity.Status != 1)
                {
                    result.Message = "只有待发布和已上线的活动可以取消";
                    return result;
                }

                // 检查活动是否已经开始（即使状态还是已上线，但实际时间已经过了开始时间）
                DateTime currentDateTime = DateTime.Now;

                // 尝试解析 DisplayDate 为 DateOnly
                if (DateOnly.TryParse(activity.DisplayDate, out DateOnly datePart))
                {
                    // 将 DateOnly 和 TimeOnly 合并为 DateTime
                    DateTime activityStartDateTime = datePart.ToDateTime(activity.StartTime);

                    // 比较当前时间是否已经过了开始时间
                    if (currentDateTime >= activityStartDateTime)
                    {
                        result.Message = "活动已经开始，无法取消";
                        return result;
                    }
                }
                else
                {
                    result.Message = "活动日期格式不正确";
                    return result;
                }


                // 查询所有有效报名的用户
                var activeMembers = await _Client.Queryable<ActivityMembers>()
                    .Where(m => m.ActivityId == activityId && m.Status == 1)
                    .ToListAsync();

                // 开启事务
                var tranResult = await _Client.Ado.UseTranAsync(async () =>
                {
                    // 1. 更新活动状态为已取消(7)并存储取消原因
                    activity.Status = 7; // 7=已取消
                    activity.UpdateAt = DateTime.Now;
                    activity.CancelReason = cancelReason; // 存储取消原因
                    await _Client.Updateable(activity).ExecuteCommandAsync();

                    // 2. 处理每个报名用户的退款
                    foreach (var member in activeMembers)
                    {
                        // 查询用户信息
                        var user = await _Client.Queryable<Users>()
                            .Where(u => u.UserID == member.UserId)
                            .FirstAsync();

                        if (user == null) continue;

                        // 查询原订单
                        var oldOrder = await _Client.Queryable<Orders>()
                            .Where(o => o.OrderID == member.OrderId)
                            .FirstAsync();

                        if (oldOrder == null) continue;

                        // 计算退款金额（根据定价类型和优惠策略）
                        decimal refundAmount = 0;

                        // 先计算理论退款金额
                        decimal theoreticalRefundAmount = 0;

                        switch (activity.PriceType)
                        {
                            case 1: // 固定价
                                // 男性按原价计算
                                decimal maleRefund = activity.Price * member.MaleNumber;

                                // 女性按优惠价计算
                                decimal femaleRefund = 0;
                                if (activity.IsLadyDiscountEnabled && member.FemaleNumber > 0)
                                {
                                    switch (activity.LadyDiscountType)
                                    {
                                        case 1: // 固定价
                                            femaleRefund = activity.LadyDiscountValue.GetValueOrDefault() * member.FemaleNumber;
                                            break;
                                        case 3: // 折扣
                                            femaleRefund = activity.Price * activity.LadyDiscountValue.GetValueOrDefault() * member.FemaleNumber;
                                            break;
                                        case 5: // 减价
                                            decimal discountedPrice = activity.Price - activity.LadyDiscountValue.GetValueOrDefault();
                                            discountedPrice = discountedPrice < 0 ? 0 : discountedPrice;
                                            femaleRefund = discountedPrice * member.FemaleNumber;
                                            break;
                                        default:
                                            femaleRefund = activity.Price * member.FemaleNumber;
                                            break;
                                    }
                                }
                                else
                                {
                                    // 如果未启用女士优惠，按原价计算
                                    femaleRefund = activity.Price * member.FemaleNumber;
                                }

                                // 总退款 = 男性退款 + 女性退款
                                theoreticalRefundAmount = maleRefund + femaleRefund;
                                break;

                            case 3: // AA制
                                // AA制中，使用DepositAmount字段作为每人押金，退还押金（按人头计算）
                                decimal depositPerPerson = activity.DepositAmount ?? 0;

                                // 男性押金退款
                                decimal maleDepositRefund = depositPerPerson * member.MaleNumber;

                                // 女性押金退款（考虑优惠）
                                decimal femaleDepositRefund = 0;
                                if (activity.IsLadyDiscountEnabled && member.FemaleNumber > 0)
                                {
                                    switch (activity.LadyDiscountType)
                                    {
                                        case 1: // 固定价
                                            femaleDepositRefund = activity.LadyDiscountValue.GetValueOrDefault() * member.FemaleNumber;
                                            break;
                                        case 3: // 折扣
                                            femaleDepositRefund = depositPerPerson * activity.LadyDiscountValue.GetValueOrDefault() * member.FemaleNumber;
                                            break;
                                        case 5: // 减价
                                            decimal discountedDeposit = depositPerPerson - activity.LadyDiscountValue.GetValueOrDefault();
                                            discountedDeposit = discountedDeposit < 0 ? 0 : discountedDeposit;
                                            femaleDepositRefund = discountedDeposit * member.FemaleNumber;
                                            break;
                                        default:
                                            femaleDepositRefund = depositPerPerson * member.FemaleNumber;
                                            break;
                                    }
                                }
                                else
                                {
                                    // 如果未启用女士优惠，按原价计算
                                    femaleDepositRefund = depositPerPerson * member.FemaleNumber;
                                }

                                // 总退款 = 男性押金退款 + 女性押金退款
                                theoreticalRefundAmount = maleDepositRefund + femaleDepositRefund;
                                break;

                            case 5: // 免费
                                theoreticalRefundAmount = 0;
                                break;

                            default:
                                theoreticalRefundAmount = activity.Price * (member.MaleNumber + member.FemaleNumber); // 默认按固定价处理
                                break;
                        }

                        // 查询用户的所有与此活动相关的订单
                        var allUserActivityOrders = await _Client.Queryable<Orders>()
                            .Where(o => o.UserId == member.UserId && o.ActivityId == activityId)
                            .ToListAsync();

                        // 计算用户实际支付的金额（减去已退款的金额）
                        decimal totalPaid = 0;
                        decimal totalRefunded = 0;

                        foreach (var order in allUserActivityOrders)
                        {
                            // 计算支付金额
                            if (order.TypeId == 5 || order.TypeId == 11) // 5=活动报名，11=订单补购
                            {
                                totalPaid += order.TotalAmount;
                            }

                            // 计算已退款金额
                            if (order.TypeId == 9 || order.TypeId == 10) // 9=订单取消退款，10=部分退款
                            {
                                totalRefunded += order.TotalAmount;
                            }

                            // 考虑部分退款的情况
                            if (order.RefundAmount.HasValue && order.RefundAmount > 0)
                            {
                                totalRefunded += order.RefundAmount.Value;
                            }
                        }

                        // 计算实际应退款金额 = 理论退款金额与实际支付金额的较小值 - 已退款金额
                        decimal actualPaidAmount = totalPaid - totalRefunded;
                        refundAmount = Math.Min(theoreticalRefundAmount, actualPaidAmount);

                        // 确保退款金额不为负数
                        refundAmount = Math.Max(0, refundAmount);

                        // 记录退款计算过程
                        await _logs.Info($"活动{activityId}取消，用户{member.UserId}退款计算：理论退款金额={theoreticalRefundAmount}，" +
                            $"总支付={totalPaid}，已退款={totalRefunded}，实际退款={refundAmount}");

                        // 更新用户余额
                        if (refundAmount > 0)
                        {
                            user.AccountBalance += refundAmount;
                            await _Client.Updateable(user).ExecuteCommandAsync();
                        }

                        // 更新订单状态
                        oldOrder.Status = 5; // 5=已退款
                        oldOrder.RefundTransaction = $"活动[{activity.Title}]已取消，退款:{refundAmount}元，\n男性{member.MaleNumber}人，女性{member.FemaleNumber}人，\n活动日期:{activity.DisplayDate}，\n活动时间:{activity.StartTime:HH:mm}-{activity.EndTime:HH:mm}，\n取消原因:{cancelReason}，\n退款时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}";
                        await _Client.Updateable(oldOrder).ExecuteCommandAsync();

                        // 创建退款订单
                        if (refundAmount > 0)
                        {
                            var refundOrder = new Orders
                            {
                                UserId = member.UserId,
                                TotalAmount = refundAmount,
                                PaymentMethod = 1,
                                PaymentTime = DateTime.Now,
                                CreatedAt = DateTime.Now,
                                TypeId = 9,  // 9=订单取消退款
                                ActivityId = activityId,
                                Status =3,  // 退款
                                RefundTransaction = $"活动[{activity.Title}]已取消退款订单，原订单ID:{oldOrder.OrderID}，退款金额:{refundAmount}元，男性{member.MaleNumber}人，女性{member.FemaleNumber}人，活动日期:{activity.DisplayDate}，活动时间:{activity.StartTime:HH:mm}-{activity.EndTime:HH:mm}，取消原因:{cancelReason}",
                            };
                            await _Client.Insertable(refundOrder).ExecuteCommandAsync();
                        }

                        // 更新报名状态
                        member.Status = 5; // 5=活动已取消
                        await _Client.Updateable(member).ExecuteCommandAsync();

                        // 记录日志
                        await _logs.Info($"活动{activityId}取消，用户{member.UserId}退款{refundAmount}");
                    }

                    //取消用户的报名情况 
                    activeMembers.Select(x => x.Status = 3);
                    //进行批量修改 
                    await _Client.Updateable(activeMembers).ExecuteCommandAsync();

                    // 创建活动取消记录日志
                    await _logs.Info($"活动{activityId}已取消，操作人ID:{operatorId}，原因:{cancelReason}，共退款{activeMembers.Count}人");
                });

                if (tranResult.IsSuccess)
                {
                    result.Success = true;
                    result.Message = $"活动已取消，已为{activeMembers.Count}名报名用户办理退款";
                }
                else
                {
                    result.Message = "取消活动失败";
                    await _logs.Error($"取消活动{activityId}失败，错误信息：{tranResult.ErrorMessage}");
                }
            }
            catch (Exception ex)
            {
                result.Message = "操作失败：" + ex.Message;
                await _logs.Error($"取消活动{activityId}失败，错误信息：{ex.Message}");
            }

            return result;
        }

        #region 定时任务方法
        /// <summary>
        /// 更新今日活动状态
        /// </summary>
        /// <returns>更新的记录数</returns>
        public async Task<int> UpdateActivitiesStatusAsync()
        {
            int updateCount = 0;

            // 获取今天的年月日
            var date = DateTime.Today.ToString("yyyy-MM-dd");

            // 获取当前时间
            TimeOnly currentTime = TimeOnly.FromDateTime(DateTime.Now);

            // 开启事务
            await _Client.Ado.UseTranAsync(async () =>
            {
                try
                {
                    // 查询今天的活动，排除未上线和已取消的活动
                    var activities = await _Client.Queryable<Activities>()
                        .Where(x => x.Status != 0 &&
                               x.Status != 7 &&
                               x.Status != 9 &&
                               x.DisplayDate.Equals(date))
                        .ToListAsync();

                    // 遍历活动，根据当前时间更新状态
                    foreach (var activity in activities)
                    {
                        switch (activity.Status)
                        {
                            // 如果状态为1(已上线)判断时间是否已经开始
                            case 1:
                                if (currentTime >= activity.StartTime)
                                {
                                    activity.Status = 3; // 改为进行中状态
                                    activity.UpdateAt = DateTime.Now;
                                }
                                break;
                            // 如果状态为3(进行中)判断时间是否已经结束
                            case 3:
                                if (currentTime >= activity.EndTime)
                                {
                                    // 检查是否为AA制活动
                                    if (activity.PriceType == 3) // 3=AA制
                                    {
                                        activity.Status = 9; // 9=已结束但是AA制待商户输入价格进行扣款
                                    }
                                    else
                                    {
                                        activity.Status = 5; // 5=已结束
                                    }
                                    activity.UpdateAt = DateTime.Now;
                                }
                                break;
                        }
                    }

                    // 更新修改过的活动
                    var activitiesToUpdate = activities.Where(a => a.UpdateAt.HasValue &&
                                              a.UpdateAt.Value.Date == DateTime.Today).ToList();

                    if (activitiesToUpdate.Any())
                    {
                        updateCount = await _Client.Updateable(activitiesToUpdate)
                            .UpdateColumns(x => new { x.Status, x.UpdateAt })
                            .ExecuteCommandAsync();

                        await _logs.Info($"活动状态已更新：{updateCount}条记录状态已更新");
                    }
                }
                catch (Exception ex)
                {
                    await _logs.Error($"更新活动状态失败：{ex.Message}");
                    throw; // 抛出异常会自动回滚事务
                }
            });

            return updateCount;
        }

        /// <summary>
        /// 更新历史活动状态
        /// </summary>
        /// <returns>更新的记录数</returns>
        public async Task<int> UpdateHistoricalActivitiesStatusAsync()
        {
            int updateCount = 0;

            // 获取当前日期
            var currentDate = DateTime.Today.ToString("yyyy-MM-dd");

            // 开启事务
            await _Client.Ado.UseTranAsync(async () =>
            {
                try
                {
                    // 查询所有过去日期的活动，排除未上线、已取消、已结束和AA制待处理的活动
                    var activities = await _Client.Queryable<Activities>()
                        .Where(x => x.Status != 0 &&
                               x.Status != 5 &&
                               x.Status != 7 &&
                               x.Status != 9 &&
                               SqlFunc.CompareTo(x.DisplayDate, currentDate) < 0)
                        .ToListAsync();

                    // 遍历活动，更新状态
                    foreach (var activity in activities)
                    {
                        // 根据活动类型设置不同的结束状态
                        if (activity.PriceType == 3) // 3=AA制
                        {
                            activity.Status = 9; // 9=已结束但是AA制待商户输入价格进行扣款
                        }
                        else
                        {
                            activity.Status = 5; // 5=已结束
                        }
                        activity.UpdateAt = DateTime.Now;
                    }

                    // 更新修改过的活动
                    var activitiesToUpdate = activities.Where(a => a.UpdateAt.HasValue &&
                                              a.UpdateAt.Value.Date == DateTime.Today).ToList();

                    if (activitiesToUpdate.Any())
                    {
                        updateCount = await _Client.Updateable(activitiesToUpdate)
                            .UpdateColumns(x => new { x.Status, x.UpdateAt })
                            .ExecuteCommandAsync();

                        // 分别记录不同类型的活动状态更新
                        int aaCount = activitiesToUpdate.Count(a => a.Status == 9);
                        int normalCount = activitiesToUpdate.Count(a => a.Status == 5);

                        await _logs.Info($"历史活动状态已更新：共{updateCount}条记录，其中普通活动{normalCount}条更新为已结束，AA制活动{aaCount}条更新为待商户输入价格");
                    }
                }
                catch (Exception ex)
                {
                    await _logs.Error($"更新历史活动状态失败：{ex.Message}");
                    throw; // 抛出异常会自动回滚事务
                }
            });

            return updateCount;
        }

        /// <summary>
        /// 结算AA制活动，对用户进行多退少补，并将费用结算给商户
        /// </summary>
        /// <param name="settlementDto">结算信息</param>
        /// <param name="venueId">球馆ID</param>
        /// <param name="operatorId">操作人ID</param>
        /// <returns>结算结果</returns>
        public async Task<ApiResult> SettleAAActivityAsync(AAActivitySettlementDto settlementDto, Guid venueId, int operatorId)
        {
            var result = new ApiResult { Success = false };

            try
            {
                // 1. 查询活动信息
                var activity = await _Client.Queryable<Activities>()
                    .Where(a => a.ActivityID == settlementDto.ActivityId)
                    .FirstAsync();

                if (activity == null)
                {
                    result.Message = "活动不存在";
                    return result;
                }

                // 2. 验证活动类型是否为AA制
                if (activity.PriceType != 3) // 3=AA制
                {
                    result.Message = "只有AA制活动才能使用此结算方式";
                    return result;
                }

                // 3. 验证活动状态是否为"已结束但是AA制待商户输入价格进行扣款"
                if (activity.Status != 9)
                {
                    result.Message = "活动状态不正确，无法进行结算";
                    return result;
                }

                // 4. 验证活动所属球馆是否匹配
                if (activity.VenueID != venueId)
                {
                    result.Message = "无权操作此活动";
                    return result;
                }

                // 5. 查询球馆信息
                var venue = await _Client.Queryable<Venues>()
                    .Where(v => v.VenueID == venueId)
                    .FirstAsync();

                if (venue == null)
                {
                    result.Message = "球馆信息不存在";
                    return result;
                }

                // 6. 查询所有参与活动的用户
                var members = await _Client.Queryable<ActivityMembers>()
                    .Where(m => m.ActivityId == settlementDto.ActivityId && m.Status == 1) // 1=正常参与状态
                    .ToListAsync();

                if (members.Count == 0)
                {
                    result.Message = "没有用户参与此活动，无需结算";
                    return result;
                }

                // 7. 计算总参与人数（考虑男女分别计算，因为可能有女性优惠）
                int totalMaleParticipants = members.Sum(m => m.MaleNumber);
                int totalFemaleParticipants = members.Sum(m => m.FemaleNumber);
                int totalParticipants = totalMaleParticipants + totalFemaleParticipants;

                // 8. 计算女性实际费用（考虑优惠）
                decimal femaleCostPerPerson = settlementDto.ActualCostPerPerson; // 默认与男性相同

                // 如果启用了女性优惠
                if (activity.IsLadyDiscountEnabled && activity.LadyDiscountType.HasValue && activity.LadyDiscountValue.HasValue)
                {
                    switch (activity.LadyDiscountType.Value)
                    {
                        case 1: // 固定价
                            femaleCostPerPerson = activity.LadyDiscountValue.Value;
                            break;
                        case 3: // 折扣
                            femaleCostPerPerson = settlementDto.ActualCostPerPerson * activity.LadyDiscountValue.Value;
                            break;
                        case 5: // 减价
                            femaleCostPerPerson = settlementDto.ActualCostPerPerson - activity.LadyDiscountValue.Value;
                            // 确保价格不为负
                            femaleCostPerPerson = Math.Max(0, femaleCostPerPerson);
                            break;
                    }
                }

                // 计算总费用（考虑男女不同价格）
                decimal totalMaleCost = settlementDto.ActualCostPerPerson * totalMaleParticipants;
                decimal totalFemaleCost = femaleCostPerPerson * totalFemaleParticipants;
                decimal totalActualCost = totalMaleCost + totalFemaleCost;

                // 开启事务
                var tranResult = await _Client.Ado.UseTranAsync(async () =>
                {
                    // 9. 更新活动信息
                    activity.Status = 5; // 5=已结束
                    activity.Price = settlementDto.ActualCostPerPerson; // 更新为实际每人费用（男性标准价）
                    activity.CostDescription = settlementDto.CostDescription; // 更新费用说明
                    activity.UpdateAt = DateTime.Now;
                    activity.IsSettled = true; // 标记为已结算
                    activity.SettlementTime = DateTime.Now;
                    await _Client.Updateable(activity).ExecuteCommandAsync();

                    // 10. 记录球馆收入
                    string discountInfo = activity.IsLadyDiscountEnabled ?
                        $"，女性{totalFemaleParticipants}人，每人{femaleCostPerPerson}元（优惠价）" : "";

                    var venueBill = new Bill
                    {
                        VenuesId = venueId,
                        ActivityId = settlementDto.ActivityId,
                        Amount = totalActualCost,
                        Type = 1, // 1=活动收入
                        Status = 1, // 1=成功
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                        Remark = $"AA制活动[{activity.Title}]结算收入，共{totalParticipants}人参与，男性{totalMaleParticipants}人，每人{settlementDto.ActualCostPerPerson}元{discountInfo}"
                    };
                    await _Client.Insertable(venueBill).ExecuteCommandAsync();

                    // 11. 更新球馆余额
                    venue.Balance += totalActualCost;
                    await _Client.Updateable(venue).ExecuteCommandAsync();

                    // 12. 处理每个用户的多退少补
                    foreach (var member in members)
                    {
                        // 查询用户信息
                        var user = await _Client.Queryable<Users>()
                            .Where(u => u.UserID == member.UserId)
                            .FirstAsync();

                        if (user == null) continue;

                        // 查询用户的所有与此活动相关的订单
                        var allUserActivityOrders = await _Client.Queryable<Orders>()
                            .Where(o => o.UserId == member.UserId && o.ActivityId == settlementDto.ActivityId)
                            .ToListAsync();

                        // 计算用户已支付的押金总额
                        decimal totalPaid = 0;
                        decimal totalRefunded = 0;

                        foreach (var order in allUserActivityOrders)
                        {
                            // 计算支付金额
                            if (order.TypeId == 5 || order.TypeId == 11) // 5=活动报名，11=订单补购
                            {
                                totalPaid += order.TotalAmount;
                            }

                            // 计算已退款金额
                            if (order.TypeId == 9 || order.TypeId == 10) // 9=订单取消退款，10=部分退款
                            {
                                totalRefunded += order.TotalAmount;
                            }

                            // 考虑部分退款的情况
                            if (order.RefundAmount.HasValue && order.RefundAmount > 0)
                            {
                                totalRefunded += order.RefundAmount.Value;
                            }
                        }

                        // 计算用户实际支付的金额（减去已退款的金额）
                        decimal actualPaidAmount = totalPaid - totalRefunded;

                        // 计算用户应付金额（考虑男女不同价格）
                        decimal userMaleCost = settlementDto.ActualCostPerPerson * member.MaleNumber;
                        decimal userFemaleCost = femaleCostPerPerson * member.FemaleNumber;
                        decimal userShouldPay = userMaleCost + userFemaleCost;

                        int userTotalParticipants = member.MaleNumber + member.FemaleNumber;

                        // 计算差额
                        decimal difference = actualPaidAmount - userShouldPay;

                        // 原订单
                        var originalOrder = allUserActivityOrders
                            .Where(o => o.TypeId == 5) // 5=活动报名
                            .OrderBy(o => o.CreatedAt)
                            .FirstOrDefault();

                        if (originalOrder == null) continue;

                        // 构建费用明细信息
                        string costDetail = $"男性{member.MaleNumber}人，每人{settlementDto.ActualCostPerPerson}元";
                        if (member.FemaleNumber > 0)
                        {
                            costDetail += $"，女性{member.FemaleNumber}人，每人{femaleCostPerPerson}元";
                            if (activity.IsLadyDiscountEnabled)
                            {
                                costDetail += "（优惠价）";
                            }
                        }

                        if (Math.Abs(difference) <= 0.01m)
                        {
                            // 差额很小，视为相等，不需要多退少补
                            continue;
                        }
                        else if (difference > 0)
                        {
                            // 需要退款给用户
                            user.AccountBalance += difference;
                            await _Client.Updateable(user).ExecuteCommandAsync();

                            // 创建退款订单
                            var refundOrder = new Orders
                            {
                                UserId = member.UserId,
                                TotalAmount = difference,
                                PaymentMethod = 1,
                                PaymentTime = DateTime.Now,
                                CreatedAt = DateTime.Now,
                                TypeId = 13, // 13=AA制结算退款
                                ActivityId = settlementDto.ActivityId,
                                Status = 3, // 3=已完成
                                RefundTransaction = $"AA制结算退款 | {activity.Title}\n金额: {difference}元\n人数: {userTotalParticipants}人\n费用明细: {costDetail}\n原押金: {actualPaidAmount}元\n实际费用: {userShouldPay}元\n日期: {activity.DisplayDate}\n时间: {activity.StartTime:HH:mm}-{activity.EndTime:HH:mm}"
                            };
                            await _Client.Insertable(refundOrder).ExecuteCommandAsync();

                            // 记录日志
                            await _logs.Info($"AA制活动{settlementDto.ActivityId}结算，用户{member.UserId}退款{difference}元，费用明细：{costDetail}");
                        }
                        else
                        {
                            // 需要用户补交费用
                            decimal additionalPayment = Math.Abs(difference);

                            // 无论余额是否足够，都直接扣除（可能导致余额为负）
                            user.AccountBalance -= additionalPayment;
                            await _Client.Updateable(user).ExecuteCommandAsync();

                            // 记录余额不足的情况，但仍然执行扣款
                            if (user.AccountBalance < 0)
                            {
                                await _logs.Warn($"AA制活动{settlementDto.ActivityId}结算，用户{member.UserId}余额不足，需补交{additionalPayment}元，扣款后余额为{user.AccountBalance}元（负数）");
                            }

                            // 创建补交订单
                            var additionalOrder = new Orders
                            {
                                UserId = member.UserId,
                                TotalAmount = additionalPayment,
                                PaymentMethod = 1,
                                PaymentTime = DateTime.Now,
                                CreatedAt = DateTime.Now,
                                TypeId = 15, // 15=AA制结算补交
                                ActivityId = settlementDto.ActivityId,
                                Status = 3, // 3=已完成
                                RefundTransaction = $"AA制结算补交 | {activity.Title}\n金额: {additionalPayment}元\n人数: {userTotalParticipants}人\n费用明细: {costDetail}\n原押金: {actualPaidAmount}元\n实际费用: {userShouldPay}元\n日期: {activity.DisplayDate}\n时间: {activity.StartTime:HH:mm}-{activity.EndTime:HH:mm}"
                            };
                            await _Client.Insertable(additionalOrder).ExecuteCommandAsync();

                            // 记录日志
                            await _logs.Info($"AA制活动{settlementDto.ActivityId}结算，用户{member.UserId}补交{additionalPayment}元，费用明细：{costDetail}");
                        }
                    }

                    // 记录活动结算日志
                    string logDiscountInfo = activity.IsLadyDiscountEnabled ?
                        $"，女性每人{femaleCostPerPerson}元（优惠价）" : "";
                    await _logs.Info($"AA制活动{settlementDto.ActivityId}结算完成，操作人:{operatorId}，总参与人数:{totalParticipants}（男{totalMaleParticipants}人，女{totalFemaleParticipants}人），男性每人{settlementDto.ActualCostPerPerson}元{logDiscountInfo}，总收入:{totalActualCost}元");
                });

                if (tranResult.IsSuccess)
                {
                    string discountMsg = activity.IsLadyDiscountEnabled ?
                        $"，女性{totalFemaleParticipants}人（优惠价{femaleCostPerPerson}元/人）" : "";
                    result.Success = true;
                    result.Message = $"活动结算成功，共{totalParticipants}人参与，男性{totalMaleParticipants}人（{settlementDto.ActualCostPerPerson}元/人）{discountMsg}，总收入{totalActualCost}元";
                }
                else
                {
                    result.Message = "结算失败：" + tranResult.ErrorMessage;
                    await _logs.Error($"AA制活动{settlementDto.ActivityId}结算失败，错误信息：{tranResult.ErrorMessage}");
                }
            }
            catch (Exception ex)
            {
                result.Message = "结算失败：" + ex.Message;
                await _logs.Error($"AA制活动{settlementDto.ActivityId}结算失败，错误信息：{ex.Message}");
            }

            return result;
        }
        #endregion

        #region 小程序API
        public async Task<PageModel<AppActivitiesDto>> AppletActiviQueryAsync(Expression<Func<Activities, Venues, FieldTypes, bool>> expressionable, int pageIndex, int pageSize)
        {
            //获取总条数
            RefAsync<int> totalCount = 0;

            // 获取当前时间
            TimeOnly currentTime = TimeOnly.FromDateTime(DateTime.Now);
            string currentDate = DateTime.Today.ToString("yyyy-MM-dd");

            var list = await _Client.Queryable<Activities>()
                            .LeftJoin<Venues>((a, b) => a.VenueID == b.VenueID)
                            .LeftJoin<FieldTypes>((a, b, c) => a.TypeId == c.FieldTypeID)
                            .WhereIF(expressionable != null, expressionable)
                            // 使用OrderByIF添加排序条件，避免语法错误
                            .OrderBy((a, b, c) => new
                            {
                                // 首先按活动状态和时间排序
                                Priority = SqlFunc.IIF(
                                    a.Status == 1 && SqlFunc.Equals(a.DisplayDate, currentDate) && a.StartTime > currentTime, 0,
                                    SqlFunc.IIF(a.Status == 1 && SqlFunc.CompareTo(a.DisplayDate, currentDate) > 0, 1,
                                    SqlFunc.IIF(a.Status == 3, 2,
                                    SqlFunc.IIF(a.Status == 1, 3,
                                    SqlFunc.IIF(a.Status == 5, 4, 5))))),
                                // 然后按日期排序
                                Date = a.DisplayDate,
                                // 最后按开始时间排序
                                Time = a.StartTime
                            })
                            .Select((a, b, c) => new AppActivitiesDto
                            {
                                Id = a.ActivityID,
                                Title = a.Title,
                                Detailed = a.Description,
                                MaxNumber = a.MaxNumber,
                                STime = a.StartTime,
                                ETime = a.EndTime,
                                Price = a.Price,
                                VIamge = b.Images,
                                VName = b.VenueName,
                                Stasus = a.Status,
                                Date = a.DisplayDate,
                                CancelReason = a.CancelReason,
                                AIamge=a.Image,
                                // 添加定价类型和优惠相关字段
                                PriceType = a.PriceType,
                                DepositAmount = a.DepositAmount,
                                IsLadyDiscountEnabled = a.IsLadyDiscountEnabled,
                                LadyDiscountType = a.LadyDiscountType,
                                LadyDiscountValue = a.LadyDiscountValue,
                                infos = SqlFunc.Subqueryable<ActivityMembers>().LeftJoin<Users>((d, e) => d.UserId == e.UserID).Where(d => d.ActivityId == a.ActivityID && d.Status == 1).ToList((d, e) => new Infos
                                {
                                    image = e.Avatar,
                                    name = e.Username,
                                    maleNumber = d.MaleNumber,
                                    femaleNumber = d.FemaleNumber
                                }),
                                SunNumber = SqlFunc.Subqueryable<ActivityMembers>().Where(e => e.ActivityId == a.ActivityID && e.Status == 1).Sum(e => e.MaleNumber + e.FemaleNumber)
                            }).ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);

            int totalPage = Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal()).ObjToInt();

            return new PageModel<AppActivitiesDto>() { count = totalCount, PageCount = totalPage, PageIndex = pageIndex, PageSize = pageSize, data = list, code = totalCount == 0 ? -1 : 0, msg = totalCount == 0 ? "未查询到任何数据" : "" };
        }

        /// <summary>
        /// 根据id返回详情的活动
        /// </summary>
        /// <param name="keyId">活动ID</param>
        /// <param name="userId">当前用户ID</param>
        /// <returns>活动详情</returns>
        public async Task<ActivitiesDetailedDto> AppleActiviGetById(int keyId, int userId)
        {
            return await _Client.Queryable<Activities>()
                .LeftJoin<Venues>((a, b) => a.VenueID == b.VenueID)
                .LeftJoin<FieldTypes>((a, b, c) => a.TypeId == c.FieldTypeID)
                .Where((a, b, c) => a.ActivityID == keyId)
                .Select((a, b, c) => new ActivitiesDetailedDto
                {
                    Id = a.ActivityID,
                    Title = a.Title,
                    Detailed = a.Description,
                    MaxNumber = a.MaxNumber,
                    STime = a.StartTime,
                    ETime = a.EndTime,
                    Price = a.Price,
                    VIamge = b.Images,
                    VName = b.VenueName,
                    Stasus = a.Status,
                    Date = a.DisplayDate,
                    AImage = a.Image,
                    CancelReason = a.CancelReason,
                    // 添加定价类型和优惠相关字段
                    PriceType = a.PriceType,
                    DepositAmount = a.DepositAmount,
                    IsLadyDiscountEnabled = a.IsLadyDiscountEnabled,
                    LadyDiscountType = a.LadyDiscountType,
                    LadyDiscountValue = a.LadyDiscountValue,
                    infos = SqlFunc.Subqueryable<ActivityMembers>().LeftJoin<Users>((d, e) => d.UserId == e.UserID).Where(d => d.ActivityId == a.ActivityID && d.Status == 1).ToList((d, e) => new Infos
                    {
                        image = e.Avatar,
                        name = e.Username,
                        maleNumber = d.MaleNumber,
                        femaleNumber = d.FemaleNumber,
                        sex = e.Sex,
                        isCurrentUser = d.UserId == userId // 添加标识当前用户的标志
                    }),
                    SunNumber = SqlFunc.Subqueryable<ActivityMembers>().Where(e => e.ActivityId == a.ActivityID && e.Status == 1).Sum(e => e.MaleNumber + e.FemaleNumber),
                    Address = b.Address, //球馆地址
                    VenunDescription = b.Description,//球馆介绍详情
                    Deadline = a.Deadline,//报名截至时间
                    UserStatus = SqlFunc.Subqueryable<ActivityMembers>().Where(f => f.UserId == userId && f.ActivityId == a.ActivityID).OrderByDesc(x => x.CreateTime).Select(x => x.Status)
                }).FirstAsync();
        }


        public async Task<bool> ApplyActivityAsync(ApplyDto dto)
        {
            try
            {
                // 用于存储新增订单的ID
                int newOrderId = 0;

                // 查询活动信息，获取定价类型
                var activity = await _Client.Queryable<Activities>()
                    .Where(a => a.ActivityID == dto.AId)
                    .FirstAsync();

                if (activity == null)
                {
                    await _logs.Error($"用户{dto.UId}报名活动{dto.AId}失败，活动不存在");
                    return false;
                }

                // 根据定价类型计算实际费用
                decimal actualPrice = 0;

                // 先计算基础价格
                switch (activity.PriceType)
                {
                    case 1: // 固定价
                        // 使用实际价格(Price)计算费用
                        // 男性按原价计算
                        decimal malePrice = activity.Price * dto.MaleNumber;

                        // 女性按优惠价计算
                        decimal femalePrice = 0;
                        if (activity.IsLadyDiscountEnabled && dto.FemaleNumber > 0)
                        {
                            switch (activity.LadyDiscountType)
                            {
                                case 1: // 固定价
                                    femalePrice = activity.LadyDiscountValue.GetValueOrDefault() * dto.FemaleNumber;
                                    break;
                                case 3: // 折扣
                                    femalePrice = activity.Price * activity.LadyDiscountValue.GetValueOrDefault() * dto.FemaleNumber;
                                    break;
                                case 5: // 减价
                                    femalePrice = (activity.Price - activity.LadyDiscountValue.GetValueOrDefault()) * dto.FemaleNumber;
                                    // 确保价格不为负数
                                    femalePrice = femalePrice < 0 ? 0 : femalePrice;
                                    break;
                                default:
                                    femalePrice = activity.Price * dto.FemaleNumber;
                                    break;
                            }
                        }
                        else
                        {
                            // 如果未启用女士优惠，按原价计算
                            femalePrice = activity.Price * dto.FemaleNumber;
                        }

                        // 总价 = 男性价格 + 女性价格
                        actualPrice = malePrice + femalePrice;
                        break;

                    case 3: // AA制
                        // AA制中，使用DepositAmount字段作为每人押金，按人头收取
                        decimal depositPerPerson = activity.DepositAmount ?? 0;

                        // AA制活动在报名时，无论男女都按原价收取押金，不应用女性优惠
                        // 女性优惠将在活动结算时再应用
                        decimal maleDeposit = depositPerPerson * dto.MaleNumber;
                        decimal femaleDeposit = depositPerPerson * dto.FemaleNumber;

                        // 总押金 = 男性押金 + 女性押金
                        actualPrice = maleDeposit + femaleDeposit;
                        break;

                    case 5: // 免费
                        actualPrice = 0;
                        break;

                    default:
                        actualPrice = activity.Price * (dto.MaleNumber + dto.FemaleNumber); // 默认按固定价处理
                        break;
                }

                var tranResult = await _Client.Ado.UseTranAsync(async () =>
                {
                    // 查询用户并修改余额
                    var user = await _Client.Queryable<Users>()
                        .Where(u => u.UserID == dto.UId)
                        .FirstAsync();

                    user.AccountBalance -= actualPrice;
                    await _Client.Updateable(user).ExecuteCommandAsync();

                    // 2. 创建订单（重点：获取插入后的订单ID）
                    var order = new Orders
                    {
                        UserId = dto.UId,
                        TotalAmount = actualPrice,
                        PaymentMethod = 1,
                        PaymentTime = DateTime.Now,
                        CreatedAt = DateTime.Now,
                        TypeId = 5,
                        ActivityId = dto.AId,
                        Status = 3,
                        RefundTransaction = $"活动报名 | {activity.Title}\n费用: {actualPrice}元\n人数: 男{dto.MaleNumber}人 女{dto.FemaleNumber}人\n日期: {activity.DisplayDate}\n时间: {activity.StartTime.ToString("HH:mm")}-{activity.EndTime.ToString("HH:mm")}"
                    };

                    // 关键：通过 ExecuteReturnIdentityAsync 获取自增主键
                    newOrderId = await _Client.Insertable(order)
                        .ExecuteReturnIdentityAsync();

                    // 1. 插入报名信息
                    var member = new ActivityMembers
                    {
                        ActivityId = dto.AId,
                        UserId = dto.UId,
                        MaleNumber = dto.MaleNumber,
                        FemaleNumber = dto.FemaleNumber,
                        Status = 1,
                        CreateTime = DateTime.Now,
                        OrderId = newOrderId,
                    };
                    await _Client.Insertable(member).ExecuteCommandAsync();
                });

                if (tranResult.IsSuccess)
                {
                    // 事务成功，可使用 newOrderId 做后续操作
                    await _logs.Info($"用户{dto.UId}成功报名活动{dto.AId}，订单ID：{newOrderId}，男性人数{dto.MaleNumber}，女性人数{dto.FemaleNumber}，实付金额{actualPrice}");
                }
                else
                {
                    // 事务失败，输出错误信息（可选）
                    await _logs.Error($"用户{dto.UId}报名活动{dto.AId}失败，事务未提交：{tranResult.ErrorMessage}");
                }

                return tranResult.IsSuccess;
            }
            catch (Exception ex)
            {
                await _logs.Error($"用户{dto.UId}报名活动{dto.AId}失败，错误信息：{ex.Message}");
                return false;
            }
        }

        public async Task<ApiResult> UpdateApplyInfoAsync(ApplyDto dto, int oldNumber, Users user)
        {
            var result = new ApiResult { Success = false };
            try
            {
                // 查询活动信息，获取定价类型
                var activity = await _Client.Queryable<Activities>()
                    .Where(a => a.ActivityID == dto.AId)
                    .FirstAsync();

                if (activity == null)
                {
                    result.Message = "活动不存在";
                    return result;
                }

                var tranResult = await _Client.Ado.UseTranAsync(async () =>
                {
                    // 查询报名信息
                    var member = await _Client.Queryable<ActivityMembers>()
                        .Where(x => x.ActivityId == dto.AId && x.UserId == dto.UId && x.Status == 1)
                        .FirstAsync();

                    if (member == null)
                    {
                        result.Message = "未找到报名信息";
                        return;
                    }

                    //检查是否存在未完成的变更
                    var existingChangeOrder = await _Client.Queryable<ActivityMemberChangeOrders>()
                        .Where(x => x.ActivityMemberId == member.Id && x.ChangeStatus != 5)
                        .FirstAsync();
                    if (existingChangeOrder != null)
                    {
                        result.Message = "存在未完成的变更，请稍后再试";
                        return;
                    }

                    // 记录原始的男女人数
                    int oldMaleNumber = member.MaleNumber;
                    int oldFemaleNumber = member.FemaleNumber;

                    // 计算实际费用差额
                    decimal actualDiff = 0;

                    switch (activity.PriceType)
                    {
                        case 1: // 固定价
                            // 计算男性价格差额
                            decimal malePriceDiff = activity.Price * (dto.MaleNumber - oldMaleNumber);

                            // 计算女性价格差额
                            decimal femalePriceDiff = 0;
                            if (activity.IsLadyDiscountEnabled)
                            {
                                decimal oldFemalePrice = 0;
                                decimal newFemalePrice = 0;

                                switch (activity.LadyDiscountType)
                                {
                                    case 1: // 固定价
                                        oldFemalePrice = activity.LadyDiscountValue.GetValueOrDefault() * oldFemaleNumber;
                                        newFemalePrice = activity.LadyDiscountValue.GetValueOrDefault() * dto.FemaleNumber;
                                        break;
                                    case 3: // 折扣
                                        oldFemalePrice = activity.Price * activity.LadyDiscountValue.GetValueOrDefault() * oldFemaleNumber;
                                        newFemalePrice = activity.Price * activity.LadyDiscountValue.GetValueOrDefault() * dto.FemaleNumber;
                                        break;
                                    case 5: // 减价
                                        decimal discountedPrice = activity.Price - activity.LadyDiscountValue.GetValueOrDefault();
                                        discountedPrice = discountedPrice < 0 ? 0 : discountedPrice;
                                        oldFemalePrice = discountedPrice * oldFemaleNumber;
                                        newFemalePrice = discountedPrice * dto.FemaleNumber;
                                        break;
                                    default:
                                        oldFemalePrice = activity.Price * oldFemaleNumber;
                                        newFemalePrice = activity.Price * dto.FemaleNumber;
                                        break;
                                }

                                femalePriceDiff = newFemalePrice - oldFemalePrice;
                            }
                            else
                            {
                                // 如果未启用女士优惠，按原价计算
                                femalePriceDiff = activity.Price * (dto.FemaleNumber - oldFemaleNumber);
                            }

                            // 总差额 = 男性价格差额 + 女性价格差额
                            actualDiff = malePriceDiff + femalePriceDiff;
                            break;

                        case 3: // AA制
                            // AA制中，使用DepositAmount字段作为每人押金，按人头收取
                            decimal depositPerPerson = activity.DepositAmount ?? 0;

                            // AA制活动在修改报名信息时，无论男女都按原价收取押金，不应用女性优惠
                            // 女性优惠将在活动结算时再应用
                            decimal maleDepositDiff = depositPerPerson * (dto.MaleNumber - oldMaleNumber);
                            decimal femaleDepositDiff = depositPerPerson * (dto.FemaleNumber - oldFemaleNumber);

                            // 总差额 = 男性押金差额 + 女性押金差额
                            actualDiff = maleDepositDiff + femaleDepositDiff;
                            break;

                        case 5: // 免费
                            actualDiff = 0;
                            break;

                        default:
                            actualDiff = activity.Price * ((dto.MaleNumber + dto.FemaleNumber) - (oldMaleNumber + oldFemaleNumber)); // 默认按固定价处理
                            break;
                    }

                    //拿当前修改的人数 减去原有的报名人数
                    int diff = (dto.MaleNumber + dto.FemaleNumber) - (oldMaleNumber + oldFemaleNumber);

                    // 查询原订单
                    var oldOrder = await _Client.Queryable<Orders>()
                        .Where(o => o.UserId == dto.UId && o.ActivityId == dto.AId && o.Status == 3 && o.TypeId==5)
                        .OrderBy(o => o.CreatedAt, OrderByType.Asc)
                        .FirstAsync();

                    // 创建变更单
                    var changeOrder = new ActivityMemberChangeOrders
                    {
                        ActivityMemberId = member.Id,
                        OriginalOrderId = oldOrder.OrderID,
                        OriginalNumbe = oldMaleNumber + oldFemaleNumber,
                        NewNumber = dto.MaleNumber + dto.FemaleNumber,
                        ChangeCount = Math.Abs(diff),
                        ChangeType = (short)(diff > 0 ? 1 : 3), // 1=增加 3=减少
                        ChangeInitiateTime = DateTime.Now,
                        ChangeStatus = 1, // 1=待处理
                        OperatorUserId = dto.UId
                    };

                    //如果有多就是添加
                    if (diff > 0)
                    {
                        // 增加人数
                        if (actualDiff > 0 && user.AccountBalance < actualDiff)
                        {
                            result.Message = "余额不足";
                            return;
                        }

                        if (actualDiff > 0)
                        {
                            user.AccountBalance -= actualDiff;
                            await _Client.Updateable(user).ExecuteCommandAsync();
                        }

                        var newOrder = new Orders
                        {
                            UserId = dto.UId,
                            TotalAmount = actualDiff,
                            PaymentMethod = 1,
                            PaymentTime = DateTime.Now,
                            CreatedAt = DateTime.Now,
                            TypeId = 11, // 11=订单补购
                            ActivityId = dto.AId,
                            Status = 3,
                            RefundTransaction = $"补购 | 活动名称:{activity.Title}\n金额: {actualDiff}元\n变化: 男{oldMaleNumber}→{dto.MaleNumber} 女{oldFemaleNumber}→{dto.FemaleNumber}\n原订单: {oldOrder.OrderID}\n活动日期: {activity.DisplayDate}\n活动时间: {activity.StartTime.ToString("HH:mm")}-{activity.EndTime.ToString("HH:mm")}",
                        };

                        var newOrderId = await _Client.Insertable(newOrder).ExecuteReturnIdentityAsync();

                        // 更新变更单
                        changeOrder.NewOrderId = newOrderId;
                        changeOrder.ChangeStatus = 5; // 5=已完成
                        changeOrder.ChangeCompleteTime = DateTime.Now;
                        await _Client.Insertable(changeOrder).ExecuteCommandAsync();

                        // 更新报名人数
                        member.MaleNumber = dto.MaleNumber;
                        member.FemaleNumber = dto.FemaleNumber;
                        await _Client.Updateable(member).ExecuteCommandAsync();

                        result.Success = true;
                        result.Message = "报名人数增加成功" + (actualDiff > 0 ? "，已扣款" : "");
                        await _logs.Info($"用户{dto.UId}成功增加活动{dto.AId}报名人数，男性从{oldMaleNumber}增加到{dto.MaleNumber}，女性从{oldFemaleNumber}增加到{dto.FemaleNumber}，实付金额{actualDiff}");
                    }
                    //如果小于零就是减少
                    else if (diff < 0)
                    {
                        // 减少人数（部分退款）
                        if (actualDiff < 0)
                        {
                            user.AccountBalance -= actualDiff; // actualDiff是负数，所以用减法
                            await _Client.Updateable(user).ExecuteCommandAsync();
                        }

                        // 记录部分退款金额
                        if (actualDiff < 0)
                        {
                            // 查询用户所有与此活动相关的订单（包括补购订单）
                            var allUserActivityOrders = await _Client.Queryable<Orders>()
                                .Where(o => o.UserId == dto.UId && o.ActivityId == dto.AId && (o.TypeId == 5 || o.TypeId == 11)) // 5=活动报名，11=订单补购
                                .OrderBy(o => o.CreatedAt)
                                .ToListAsync();
                            
                            // 计算用户总支付金额
                            decimal totalPaid = allUserActivityOrders.Sum(o => o.TotalAmount);
                            
                            // 查询已退款金额
                            var refundOrders = await _Client.Queryable<Orders>()
                                .Where(o => o.UserId == dto.UId && o.ActivityId == dto.AId && (o.TypeId == 9 || o.TypeId == 10)) // 9=订单取消退款，10=部分退款
                                .ToListAsync();
                            
                            decimal totalRefunded = refundOrders.Sum(o => Math.Abs(o.TotalAmount));
                            
                            // 加上订单中已记录的部分退款金额
                            totalRefunded += allUserActivityOrders.Where(o => o.RefundAmount.HasValue).Sum(o => o.RefundAmount.Value);
                            
                            // 计算当前退款后的剩余支付金额
                            decimal remainingPaid = totalPaid - totalRefunded - (-actualDiff);
                            
                            // 记录补购信息
                            string supplementInfo = "";
                            if (allUserActivityOrders.Count > 1)
                            {
                                var supplementOrders = allUserActivityOrders.Where(o => o.TypeId == 11).ToList();
                                if (supplementOrders.Any())
                                {
                                    supplementInfo = $"，包含补购订单:{string.Join(",", supplementOrders.Select(o => o.OrderID))}";
                                }
                            }
                            
                            // 记录退款信息
                            string refundInfo = $"部分退款 | 活动名称:{activity.Title}\n金额: {-actualDiff}元\n变化: 男{oldMaleNumber}→{dto.MaleNumber} 女{oldFemaleNumber}→{dto.FemaleNumber}\n时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}{(string.IsNullOrEmpty(supplementInfo) ? "" : "\n" + supplementInfo)}";
                            
                            // 如果退款后剩余金额接近0，则标记为全额退款
                            if (remainingPaid <= 0.01m)
                            {
                                // 更新所有相关订单状态为已退款
                                foreach (var order in allUserActivityOrders)
                                {
                                    if (order.Status != 5) // 如果不是已退款状态
                                    {
                                        order.Status = 5; // 5=已退款
                                        order.RefundTransaction = refundInfo + "\n状态: 全额退款";
                                        await _Client.Updateable(order).ExecuteCommandAsync();
                                    }
                                }
                            }
                            else
                            {
                                // 只记录部分退款金额，不修改订单状态
                                oldOrder.RefundAmount = (-actualDiff) + (oldOrder.RefundAmount ?? 0); // actualDiff是负数，所以取反
                                oldOrder.RefundTransaction = refundInfo + $"\n状态: 部分退款\n剩余金额: {remainingPaid:F2}元";
                                await _Client.Updateable(oldOrder).ExecuteCommandAsync();
                            }
                        }

                        // 添加退款订单
                        var refundOrder = new Orders
                        {
                            UserId = dto.UId,
                            TotalAmount = actualDiff, // actualDiff是负数
                            PaymentMethod = 1,
                            PaymentTime = DateTime.Now,
                            CreatedAt = DateTime.Now,
                            TypeId = 10, // 10=部分退款
                            ActivityId = dto.AId,
                            Status = 3, // 退款
                            RefundTransaction = $"部分退款 | 活动名称:{activity.Title}\n金额: {-actualDiff}元\n变化: 男{oldMaleNumber}→{dto.MaleNumber} 女{oldFemaleNumber}→{dto.FemaleNumber}\n原订单: {oldOrder.OrderID}\n活动日期: {activity.DisplayDate}\n活动时间: {activity.StartTime.ToString("HH:mm")}-{activity.EndTime.ToString("HH:mm")}"
                        };
                        var newOrderId = await _Client.Insertable(refundOrder).ExecuteReturnIdentityAsync();

                        // 更新变更单（增加RefundOrderId字段）
                        changeOrder.NewOrderId = newOrderId;
                        changeOrder.ChangeStatus = 5; // 5=已完成
                        changeOrder.ChangeCompleteTime = DateTime.Now;
                        changeOrder.RefundOrderId = newOrderId;
                        await _Client.Insertable(changeOrder).ExecuteCommandAsync();

                        // 更新报名人数
                        member.MaleNumber = dto.MaleNumber;
                        member.FemaleNumber = dto.FemaleNumber;
                        await _Client.Updateable(member).ExecuteCommandAsync();

                        result.Success = true;
                        result.Message = "报名人数减少成功" + (actualDiff < 0 ? "，已退款" : "");
                        await _logs.Info($"用户{dto.UId}成功减少活动{dto.AId}报名人数，男性从{oldMaleNumber}减少到{dto.MaleNumber}，女性从{oldFemaleNumber}减少到{dto.FemaleNumber}，退款金额{-actualDiff}");
                    }
                    //还有一种可能就是男女比列可能变了
                    else
                    {
                        // 总人数未变，但可能男女比例变化
                        if (oldMaleNumber != dto.MaleNumber || oldFemaleNumber != dto.FemaleNumber)
                        {
                            // 计算价格差异
                            if (actualDiff > 0)
                            {
                                // 需要额外付款
                                if (user.AccountBalance < actualDiff)
                                {
                                    result.Message = "余额不足";
                                    return;
                                }

                                user.AccountBalance -= actualDiff;
                                await _Client.Updateable(user).ExecuteCommandAsync();

                                var newOrder = new Orders
                                {
                                    UserId = dto.UId,
                                    TotalAmount = actualDiff,
                                    PaymentMethod = 1,
                                    PaymentTime = DateTime.Now,
                                    CreatedAt = DateTime.Now,
                                    TypeId = 11, // 11=订单补购
                                    ActivityId = dto.AId,
                                    Status = 3,
                                    RefundTransaction = $"性别比例调整 | 活动名称:{activity.Title}\n金额: {actualDiff}元\n变化: 男{oldMaleNumber}→{dto.MaleNumber} 女{oldFemaleNumber}→{dto.FemaleNumber}\n原订单: {oldOrder.OrderID}\n活动日期: {activity.DisplayDate}\n活动时间: {activity.StartTime.ToString("HH:mm")}-{activity.EndTime.ToString("HH:mm")}",
                                };

                                var newOrderId = await _Client.Insertable(newOrder).ExecuteReturnIdentityAsync();

                                // 更新变更单
                                changeOrder.NewOrderId = newOrderId;
                                changeOrder.ChangeStatus = 5; // 5=已完成
                                changeOrder.ChangeCompleteTime = DateTime.Now;
                                await _Client.Insertable(changeOrder).ExecuteCommandAsync();

                                result.Message = "报名人数比例调整成功，已补差价";
                            }
                            else if (actualDiff < 0)
                            {
                                // 需要退款
                                user.AccountBalance -= actualDiff; // actualDiff是负数，所以用减法
                                await _Client.Updateable(user).ExecuteCommandAsync();
                                
                                // 查询用户所有与此活动相关的订单（包括补购订单）
                                var allUserActivityOrders = await _Client.Queryable<Orders>()
                                    .Where(o => o.UserId == dto.UId && o.ActivityId == dto.AId && (o.TypeId == 5 || o.TypeId == 11)) // 5=活动报名，11=订单补购
                                    .OrderBy(o => o.CreatedAt)
                                    .ToListAsync();
                                
                                // 计算用户总支付金额
                                decimal totalPaid = allUserActivityOrders.Sum(o => o.TotalAmount);
                                
                                // 查询已退款金额
                                var refundOrders = await _Client.Queryable<Orders>()
                                    .Where(o => o.UserId == dto.UId && o.ActivityId == dto.AId && (o.TypeId == 9 || o.TypeId == 10)) // 9=订单取消退款，10=部分退款
                                    .ToListAsync();
                                
                                decimal totalRefunded = refundOrders.Sum(o => Math.Abs(o.TotalAmount));
                                
                                // 加上订单中已记录的部分退款金额
                                totalRefunded += allUserActivityOrders.Where(o => o.RefundAmount.HasValue).Sum(o => o.RefundAmount.Value);
                                
                                // 计算当前退款后的剩余支付金额
                                decimal remainingPaid = totalPaid - totalRefunded - (-actualDiff);
                                
                                // 记录补购信息
                                string supplementInfo = "";
                                if (allUserActivityOrders.Count > 1)
                                {
                                    var supplementOrders = allUserActivityOrders.Where(o => o.TypeId == 11).ToList();
                                    if (supplementOrders.Any())
                                    {
                                        supplementInfo = $"，包含补购订单:{string.Join(",", supplementOrders.Select(o => o.OrderID))}";
                                    }
                                }
                                
                                // 记录退款信息
                                string refundInfo = $"性别比例调整 | {activity.Title}\n金额: {-actualDiff}元\n变化: 男{oldMaleNumber}→{dto.MaleNumber} 女{oldFemaleNumber}→{dto.FemaleNumber}\n时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}{(string.IsNullOrEmpty(supplementInfo) ? "" : "\n补购订单: " + supplementInfo.Replace("，包含补购订单:", ""))}";
                                
                                // 如果退款后剩余金额接近0，则标记为全额退款
                                if (remainingPaid <= 0.01m)
                                {
                                    // 更新所有相关订单状态为已退款
                                    foreach (var order in allUserActivityOrders)
                                    {
                                        if (order.Status != 5) // 如果不是已退款状态
                                        {
                                            order.Status = 5; // 5=已退款
                                            order.RefundTransaction = refundInfo + "，全额退款";
                                            await _Client.Updateable(order).ExecuteCommandAsync();
                                        }
                                    }
                                }
                                else
                                {
                                    // 只记录部分退款金额，不修改订单状态
                                    oldOrder.RefundAmount = (-actualDiff) + (oldOrder.RefundAmount ?? 0); // actualDiff是负数，所以取反
                                    oldOrder.RefundTransaction = refundInfo + $"，部分退款(剩余未退款金额:{remainingPaid:F2}元)";
                                    await _Client.Updateable(oldOrder).ExecuteCommandAsync();
                                }

                                // 添加退款订单
                                var refundOrder = new Orders
                                {
                                    UserId = dto.UId,
                                    TotalAmount = actualDiff, // actualDiff是负数
                                    PaymentMethod = 1,
                                    PaymentTime = DateTime.Now,
                                    CreatedAt = DateTime.Now,
                                    TypeId = 10, // 10=部分退款
                                    ActivityId = dto.AId,
                                    Status = 3, // 退款
                                    RefundTransaction = $"性别比例调整 |活动名称:{activity.Title}\n金额: {-actualDiff}元\n变化: 男{oldMaleNumber}→{dto.MaleNumber} 女{oldFemaleNumber}→{dto.FemaleNumber}\n原订单: {oldOrder.OrderID}\n活动日期: {activity.DisplayDate}\n活动时间: {activity.StartTime.ToString("HH:mm")}-{activity.EndTime.ToString("HH:mm")}"
                                };
                                var newOrderId = await _Client.Insertable(refundOrder).ExecuteReturnIdentityAsync();

                                // 更新变更单
                                changeOrder.NewOrderId = newOrderId;
                                changeOrder.ChangeStatus = 5; // 5=已完成
                                changeOrder.ChangeCompleteTime = DateTime.Now;
                                changeOrder.RefundOrderId = newOrderId;
                                await _Client.Insertable(changeOrder).ExecuteCommandAsync();

                                result.Message = "报名人数比例调整成功，已退差价";
                            }
                            else
                            {
                                // 价格不变，只更新变更单
                                changeOrder.ChangeStatus = 5; // 5=已完成
                                changeOrder.ChangeCompleteTime = DateTime.Now;
                                await _Client.Insertable(changeOrder).ExecuteCommandAsync();

                                result.Message = "报名人数比例调整成功";
                            }

                            member.MaleNumber = dto.MaleNumber;
                            member.FemaleNumber = dto.FemaleNumber;
                            await _Client.Updateable(member).ExecuteCommandAsync();

                            result.Success = true;
                            await _logs.Info($"用户{dto.UId}调整活动{dto.AId}报名男女比例，男性从{oldMaleNumber}变为{dto.MaleNumber}，女性从{oldFemaleNumber}变为{dto.FemaleNumber}，价格差异{actualDiff}");
                        }
                        else
                        {
                            result.Message = "报名人数未变化";
                            await _logs.Info($"用户{dto.UId}活动{dto.AId}报名人数未发生变化");
                        }
                    }
                });

                if (!tranResult.IsSuccess && string.IsNullOrEmpty(result.Message))
                {
                    result.Message = "操作失败";
                    await _logs.Error($"用户{dto.UId}修改活动{dto.AId}报名信息失败，错误信息：操作失败");
                }
            }
            catch (Exception ex)
            {
                result.Message = "操作失败：" + ex.Message;
                await _logs.Error($"用户{dto.UId}修改活动{dto.AId}报名信息失败，错误信息：{ex.Message}");
            }
            return result;
        }

        public async Task<ApiResult> CancelApplyAsync(CancelApplyDto dto, ActivityMembers member, Orders oldOrder, Users user)
        {
            var result = new ApiResult { Success = false };
            try
            {
                // 查询活动信息，获取定价类型
                var activity = await _Client.Queryable<Activities>()
                    .Where(a => a.ActivityID == dto.ActivityId)
                    .FirstAsync();

                if (activity == null)
                {
                    result.Message = "活动不存在";
                    return result;
                }

                // 根据定价类型计算实际退款金额
                decimal actualRefundAmount = 0;
                switch (activity.PriceType)
                {
                    case 1: // 固定价
                        // 男性按原价计算
                        decimal maleRefund = activity.Price * member.MaleNumber;

                        // 女性按优惠价计算
                        decimal femaleRefund = 0;
                        if (activity.IsLadyDiscountEnabled && member.FemaleNumber > 0)
                        {
                            switch (activity.LadyDiscountType)
                            {
                                case 1: // 固定价
                                    femaleRefund = activity.LadyDiscountValue.GetValueOrDefault() * member.FemaleNumber;
                                    break;
                                case 3: // 折扣
                                    femaleRefund = activity.Price * activity.LadyDiscountValue.GetValueOrDefault() * member.FemaleNumber;
                                    break;
                                case 5: // 减价
                                    decimal discountedPrice = activity.Price - activity.LadyDiscountValue.GetValueOrDefault();
                                    discountedPrice = discountedPrice < 0 ? 0 : discountedPrice;
                                    femaleRefund = discountedPrice * member.FemaleNumber;
                                    break;
                                default:
                                    femaleRefund = activity.Price * member.FemaleNumber;
                                    break;
                            }
                        }
                        else
                        {
                            // 如果未启用女士优惠，按原价计算
                            femaleRefund = activity.Price * member.FemaleNumber;
                        }

                        // 总退款 = 男性退款 + 女性退款
                        actualRefundAmount = maleRefund + femaleRefund;
                        break;

                    case 3: // AA制
                        // AA制中，使用DepositAmount字段作为每人押金，退还押金（按人头计算）
                        decimal depositPerPerson = activity.DepositAmount ?? 0;

                        // AA制活动在取消报名时，无论男女都按原价退还押金，不应用女性优惠
                        // 女性优惠只在最终结算时应用
                        decimal maleDepositRefund = depositPerPerson * member.MaleNumber;
                        decimal femaleDepositRefund = depositPerPerson * member.FemaleNumber;

                        // 总退款 = 男性押金退款 + 女性押金退款
                        actualRefundAmount = maleDepositRefund + femaleDepositRefund;
                        break;

                    case 5: // 免费
                        actualRefundAmount = 0;
                        break;

                    default:
                        actualRefundAmount = activity.Price * (member.MaleNumber + member.FemaleNumber); // 默认按固定价处理
                        break;
                }

                var tranResult = await _Client.Ado.UseTranAsync(async () =>
                {
                    // 2. 创建取消报名变更单
                    var cancelChangeOrder = new ActivityMemberChangeOrders
                    {
                        ActivityMemberId = member.Id,
                        OriginalOrderId = oldOrder.OrderID,
                        OriginalNumbe = member.MaleNumber + member.FemaleNumber,  // 原报名人数
                        NewNumber = 0,                       // 新人数=0（取消）
                        ChangeCount = member.MaleNumber + member.FemaleNumber,  // 减少人数=原人数
                        ChangeType = 5,                      // 5=取消报名
                        ChangeInitiateTime = DateTime.Now,
                        ChangeStatus = 1,                    // 待处理
                        OperatorUserId = dto.UserId,
                        Remark = "用户取消报名"
                    };
                    // 插入变更单并获取自增ID
                    cancelChangeOrder.ChangeOrderId = await _Client.Insertable(cancelChangeOrder)
                        .ExecuteReturnIdentityAsync();

                    // 查询用户所有与此活动相关的订单（包括补购订单）
                    var allUserActivityOrders = await _Client.Queryable<Orders>()
                        .Where(o => o.UserId == dto.UserId && o.ActivityId == dto.ActivityId && (o.TypeId == 5 || o.TypeId == 11)) // 5=活动报名，11=订单补购
                        .OrderBy(o => o.CreatedAt)
                        .ToListAsync();
                    
                    // 记录补购信息
                    string supplementInfo = "";
                    if (allUserActivityOrders.Count > 1)
                    {
                        var supplementOrders = allUserActivityOrders.Where(o => o.TypeId == 11).ToList();
                        if (supplementOrders.Any())
                        {
                            supplementInfo = $"，包含补购订单:{string.Join(",", supplementOrders.Select(o => o.OrderID))}";
                        }
                    }
                    
                    // 3. 更新用户余额
                    if (actualRefundAmount > 0)
                    {
                        user.AccountBalance += actualRefundAmount;
                        await _Client.Updateable(user).ExecuteCommandAsync();
                    }

                    // 4. 更新所有相关订单状态为已退款
                    foreach (var order in allUserActivityOrders)
                    {
                        if (order.Status != 5) // 如果不是已退款状态
                        {
                            order.Status = 5; // 5=已退款
                            order.RefundTransaction = $"取消报名 | {activity.Title}\n金额: {actualRefundAmount}元\n人数: 男{member.MaleNumber}人 女{member.FemaleNumber}人\n状态: 全额退款\n时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}{(string.IsNullOrEmpty(supplementInfo) ? "" : "\n补购订单: " + supplementInfo.Replace("，包含补购订单:", ""))}";
                            await _Client.Updateable(order).ExecuteCommandAsync();
                        }
                    }

                    // 5. 创建退款订单（关联到变更单）
                    var refundOrder = new Orders
                    {
                        UserId = dto.UserId,
                        TotalAmount = actualRefundAmount,
                        PaymentMethod = 1,
                        PaymentTime = DateTime.Now,
                        CreatedAt = DateTime.Now,
                        TypeId = 9,  // 9=订单取消退款
                        ActivityId = dto.ActivityId,
                        Status = 3,  // 退款
                        RefundTransaction = $"取消报名 | {activity.Title}\n金额: {actualRefundAmount}元\n人数: 男{member.MaleNumber}人 女{member.FemaleNumber}人\n原订单: {string.Join(",", allUserActivityOrders.Select(o => o.OrderID))}\n日期: {activity.DisplayDate}\n时间: {activity.StartTime.ToString("HH:mm")}-{activity.EndTime.ToString("HH:mm")}{(string.IsNullOrEmpty(supplementInfo) ? "" : "\n补购订单: " + supplementInfo.Replace("，包含补购订单:", ""))}",
                        RelatedChangeOrderId = cancelChangeOrder.ChangeOrderId  // 新增字段关联变更单
                    };
                    int newOrderId = await _Client.Insertable(refundOrder).ExecuteReturnIdentityAsync();

                    // 6. 更新变更单状态（关联退款订单）
                    cancelChangeOrder.NewOrderId = newOrderId;
                    cancelChangeOrder.ChangeStatus = 5; // 已完成
                    cancelChangeOrder.ChangeCompleteTime = DateTime.Now;
                    await _Client.Updateable(cancelChangeOrder).ExecuteCommandAsync();

                    // 7. 更新报名状态
                    member.Status = 3; // 3=已取消
                    await _Client.Updateable(member).ExecuteCommandAsync();
                });

                if (tranResult.IsSuccess)
                {
                    result.Success = true;
                    result.Message = "取消报名成功" + (actualRefundAmount > 0 ? "，已退款" : "");
                    await _logs.Info($"用户{dto.UserId}成功取消活动{dto.ActivityId}报名，退款金额{actualRefundAmount}");
                }
                else
                {
                    result.Message = "取消报名失败";
                    await _logs.Error($"用户{dto.UserId}取消活动{dto.ActivityId}报名失败，错误信息：取消报名失败");
                }
            }
            catch (Exception ex)
            {
                result.Message = "操作失败：" + ex.Message;
                await _logs.Error($"用户{dto.UserId}取消活动{dto.ActivityId}报名失败，错误信息：{ex.Message}");
            }
            return result;
        }


        /// <summary>
        /// 获取用户参与的活动列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户活动列表</returns>
        public async Task<UserActivityListDto> GetUserActivitiesAsync(int userId)
        {
            var result = new UserActivityListDto();

            try
            {
                // 获取用户所有参与的活动记录（包括已取消的）
                var activityMembers = await _Client.Queryable<ActivityMembers>()
                    .Where(m => m.UserId == userId)
                    .ToListAsync();

                if (activityMembers == null || !activityMembers.Any())
                    return result;

                // 获取所有相关活动的ID
                var activityIds = activityMembers.Select(m => m.ActivityId).Distinct().ToList();

                // 查询活动详情（包含女性优惠信息和价格类型）
                var activities = await _Client.Queryable<Activities>()
                    .LeftJoin<Venues>((a, v) => a.VenueID == v.VenueID)
                    .Where(a => activityIds.Contains(a.ActivityID))
                    .Select((a, v) => new
                    {
                        a.ActivityID,
                        a.Title,
                        a.DisplayDate,
                        a.StartTime,
                        a.EndTime,
                        a.Status,
                        a.Image,
                        a.Price,
                        a.PriceType,
                        a.DepositAmount,
                        a.IsLadyDiscountEnabled,
                        a.LadyDiscountType,
                        a.LadyDiscountValue,
                        v.VenueName,
                        v.Address
                    })
                    .ToListAsync();

                // 查询所有相关订单信息，用于计算实际支付和退款金额
                var allOrders = await _Client.Queryable<Orders>()
                    .Where(o => o.UserId == userId && activityIds.Contains(o.ActivityId ?? 0))
                    .ToListAsync();

                // 将活动和用户报名信息关联
                foreach (var member in activityMembers)
                {
                    var activity = activities.FirstOrDefault(a => a.ActivityID == member.ActivityId);
                    if (activity == null) continue;

                    // 计算实际支付金额和退款金额
                    decimal actualPaid = 0;
                    decimal refundAmount = 0;

                    // 获取与此活动相关的所有订单
                    var activityOrders = allOrders.Where(o => o.ActivityId == member.ActivityId).ToList();

                    // 计算支付金额（活动报名和补购）
                    foreach (var order in activityOrders.Where(o => o.TypeId == 5 || o.TypeId == 11 || o.TypeId == 15)) // 5=活动报名，11=订单补购，15=AA制结算补交
                    {
                        actualPaid += order.TotalAmount;
                    }

                    // 计算退款金额（取消报名、部分退款和AA制结算退款）
                    foreach (var order in activityOrders.Where(o => o.TypeId == 9 || o.TypeId == 10 || o.TypeId == 13)) // 9=订单取消退款，10=部分退款，13=AA制结算退款
                    {
                        refundAmount += order.TotalAmount;
                    }

                    // 考虑部分退款的情况
                    foreach (var order in activityOrders.Where(o => o.RefundAmount.HasValue && o.RefundAmount > 0))
                    {
                        refundAmount += order.RefundAmount.Value;
                    }

                    var userActivity = new UserActivityDto
                    {
                        ActivityId = activity.ActivityID,
                        Title = activity.Title,
                        Date = activity.DisplayDate,
                        Time = $"{activity.StartTime.ToString("HH:mm")}-{activity.EndTime.ToString("HH:mm")}",
                        Status = member.Status,
                        Image = activity.Image,
                        MaleNumber = member.MaleNumber,
                        FemaleNumber = member.FemaleNumber,
                        // 添加价格和优惠信息
                        Price = activity.Price,
                        PriceType = activity.PriceType,
                        DepositAmount = activity.DepositAmount,
                        IsLadyDiscountEnabled = activity.IsLadyDiscountEnabled,
                        LadyDiscountType = activity.LadyDiscountType,
                        LadyDiscountValue = activity.LadyDiscountValue,
                        // 添加支付和退款金额
                        ActualPaid = actualPaid,
                        RefundAmount = refundAmount,
                        // 添加场馆信息
                        VenueName = activity.VenueName,
                        VenueAddress = activity.Address,
                        // 添加订单ID（取第一个报名订单）
                        OrderId = activityOrders.FirstOrDefault(o => o.TypeId == 5)?.OrderID ?? 0
                    };

                    // 设置状态文本
                    switch (member.Status)
                    {
                        case 1: // 正常报名状态
                            switch (activity.Status)
                            {
                                case 1: // 已上线
                                    userActivity.StatusText = "报名中";
                                    result.OngoingActivities.Add(userActivity);
                                    break;
                                case 3: // 进行中
                                    userActivity.StatusText = "进行中";
                                    result.OngoingActivities.Add(userActivity);
                                    break;
                                case 5: // 已结束
                                    userActivity.StatusText = "已完成";
                                    result.CompletedActivities.Add(userActivity);
                                    break;
                                case 9: // AA制待结算
                                    userActivity.StatusText = "待结算";
                                    result.OngoingActivities.Add(userActivity);
                                    break;
                                default:
                                    userActivity.StatusText = "进行中";
                                    result.OngoingActivities.Add(userActivity);
                                    break;
                            }
                            break;
                        case 3: // 已取消
                            userActivity.StatusText = "已取消";
                            result.CancelledActivities.Add(userActivity);
                            break;
                        default:
                            userActivity.StatusText = "未知状态";
                            result.OngoingActivities.Add(userActivity);
                            break;
                    }
                }

                // 对每个列表按日期排序
                result.OngoingActivities = result.OngoingActivities
                    .OrderBy(a => a.Date)
                    .ThenBy(a => a.Time)
                    .ToList();

                result.CompletedActivities = result.CompletedActivities
                    .OrderByDescending(a => a.Date)
                    .ThenBy(a => a.Time)
                    .ToList();

                result.CancelledActivities = result.CancelledActivities
                    .OrderByDescending(a => a.Date)
                    .ThenBy(a => a.Time)
                    .ToList();
            }
            catch (Exception ex)
            {
                await _logs.Error($"获取用户活动列表失败，用户ID：{userId}，错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 小程序端创建活动
        /// </summary>
        /// <param name="dto">活动信息</param>
        /// <param name="venueId">球馆ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>创建结果</returns>
        public async Task<ApiResult> CreateActivityAsync(ActivityCreateDto dto, Guid venueId, int userId)
        {
            var result = new ApiResult { Success = false };

            try
            {
                // 验证球馆是否存在
                var venue = await _Client.Queryable<Venues>()
                    .Where(v => v.VenueID == venueId && v.IsDeleted == 1) // 1=正常营业
                    .FirstAsync();

                if (venue == null)
                {
                    result.Message = "球馆不存在或未正常营业";
                    return result;
                }

                // 验证活动类型是否存在
                var fieldType = await _Client.Queryable<FieldTypes>()
                    .Where(t => t.FieldTypeID == dto.TypeId && t.IsDeleted == false)
                    .FirstAsync();

                if (fieldType == null)
                {
                    result.Message = "活动类型不存在";
                    return result;
                }

                // 验证时间格式和有效性
                if (!dto.DisplayDate.IsValidIsoDate())
                {
                    result.Message = "日期格式无效，请使用yyyy-MM-dd格式";
                    return result;
                }

                // 验证开始时间必须早于结束时间
                if (dto.StartTime >= dto.EndTime)
                {
                    result.Message = "开始时间必须早于结束时间";
                    return result;
                }

                // 验证活动日期必须是当前日期或未来日期
                DateTime activityDate = DateTime.Parse(dto.DisplayDate);
                if (activityDate.Date < DateTime.Today)
                {
                    result.Message = "活动日期不能是过去的日期";
                    return result;
                }

                // 验证活动价格必须大于等于0
                if (dto.Price < 0)
                {
                    result.Message = "活动价格不能为负数";
                    return result;
                }

                // 创建活动实体
                var activity = new Activities
                {
                    Title = dto.Title,
                    Description = dto.Description,
                    DisplayDate = dto.DisplayDate,
                    StartTime = dto.StartTime,
                    EndTime = dto.EndTime,
                    MaxNumber = dto.MaxNumber,
                    Price = dto.Price,
                    DepositAmount = dto.DepositAmount,
                    PriceType = dto.PriceType,
                    IsLadyDiscountEnabled = dto.IsLadyDiscountEnabled,
                    LadyDiscountType = dto.LadyDiscountType,
                    LadyDiscountValue = dto.LadyDiscountValue,
                    Deadline = dto.Deadline,
                    TypeId = dto.TypeId,
                    Image = dto.Image,
                    VenueID = venueId,
                    Status = 1, // 1=已上线
                    CreatedAt = DateTime.Now,
                    IsSettled = false, // 默认未结算
                };

                // 开启事务
                await _Client.Ado.BeginTranAsync();

                // 插入活动
                var insertResult = await _Client.Insertable(activity).ExecuteCommandAsync() > 0;

                if (!insertResult)
                {
                    await _Client.Ado.RollbackTranAsync();
                    result.Message = "创建活动失败";
                    return result;
                }

                // 提交事务
                await _Client.Ado.CommitTranAsync();

                result.Success = true;
                result.Message = "活动创建成功";
                await _logs.Info($"用户{userId}成功创建活动：{dto.Title}");
            }
            catch (Exception ex)
            {
                await _Client.Ado.RollbackTranAsync();
                result.Message = "创建活动失败：" + ex.Message;
                await _logs.Error($"用户{userId}创建活动失败：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 获取活动类型列表
        /// </summary>
        /// <returns>活动类型列表</returns>
        public async Task<List<FieldTypeOption>> GetFieldTypesAsync()
        {
            try
            {
                var types = await _Client.Queryable<FieldTypes>()
                    .Where(t => !t.IsDeleted)
                    .Select(t => new FieldTypeOption
                    {
                        Id = t.FieldTypeID,
                        Name = t.FieldTypeName
                    })
                    .ToListAsync();

                return types;
            }
            catch (Exception ex)
            {
                await _logs.Error($"获取活动类型失败：{ex.Message}");
                return new List<FieldTypeOption>();
            }
        }

        #endregion



    }
}
